package com.cljz.makepassenger.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.R;
import com.cljz.makepassenger.base.BaseActivity;
import com.cljz.makepassenger.model.net.bean.GetUserInfoBean;
import com.cljz.makepassenger.present.activity.GroupDetailsP;
import com.cljz.makepassenger.ui.adapter.GroupMemberListAdapter;
import com.cljz.makepassenger.utils.CommonUtils;
import com.cljz.makepassenger.utils.T;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCursorResult;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMPushConfigs;
import com.hyphenate.exceptions.HyphenateException;
import com.jakewharton.rxbinding.view.RxView;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.router.Router;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by apple on 2017/5/13.
 */

public class GroupDetailsActivity extends BaseActivity<GroupDetailsP> implements GroupMemberListAdapter.OnItemClickListener {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.fl_back)
    FrameLayout flBack;
    @BindView(R.id.tv_title_name)
    TextView tvTitleName;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.fl_title_right)
    FrameLayout flTitleRight;
    @BindView(R.id.iv_title_right1)
    ImageView ivTitleRight1;
    @BindView(R.id.fl_title_right1)
    FrameLayout flTitleRight1;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.tv_group_name)
    TextView tvGroupName;
    @BindView(R.id.switch_group_msg)
    Switch switchGroupMsg;
    @BindView(R.id.xrv_group_mem)
    XRecyclerView xrvGroupMem;
    @BindView(R.id.rl_switch_block_group_msg)
    RelativeLayout rlSwitchBlockGroupMsg;
    private String groupId;
    private EMGroup group;
    private EMPushConfigs pushConfigs;
    private List<GetUserInfoBean.DataBean> groupMemberList;
    private Boolean isOwner;
    private GroupMemberListAdapter groupMemberListAdapter;
    private String titleGroupName;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 233 && resultCode == RESULT_OK) {
            getGroupFromServer();

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void getGroupFromServer() {
        Observable.create(new Observable.OnSubscribe<EMGroup>() {
            @Override
            public void call(Subscriber<? super EMGroup> subscriber) {
                try {
                    //根据群组ID从服务器获取群组基本信息
                    EMGroup group = EMClient.getInstance().groupManager().getGroupFromServer(groupId);
                    subscriber.onNext(group);
                } catch (HyphenateException e) {
                    subscriber.onNext(null);
                    e.printStackTrace();
                }

            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<EMGroup>bindToLifecycle())
                .subscribe(new Action1<EMGroup>() {
                    @Override
                    public void call(EMGroup emGroup) {
                        if (emGroup != null) {
                            group = emGroup;
                        } else {
                            group = EMClient.getInstance().groupManager().getGroup(groupId);
                        }
                        if (group.getGroupName().length() > 8) {
                            titleGroupName = group.getGroupName().substring(0, 8) + "...";
                        } else {
                            titleGroupName = group.getGroupName();
                        }
                        tvTitleName.setText(titleGroupName);
                        tvGroupName.setText(group.getGroupName());

                        pushConfigs = EMClient.getInstance().pushManager().getPushConfigs();
                        isOwner = EMClient.getInstance().getCurrentUser().equals(group.getOwner());
                        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(GroupDetailsActivity.this);
                        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                        xrvGroupMem.setLayoutManager(linearLayoutManager);
                        groupMemberListAdapter = new GroupMemberListAdapter(GroupDetailsActivity.this, groupMemberList, isOwner);
                        groupMemberListAdapter.setOnItemClickListener(GroupDetailsActivity.this);
                        xrvGroupMem.setAdapter(groupMemberListAdapter);
                        xrvGroupMem.setPullRefreshEnabled(false);
                        xrvGroupMem.setLoadingMoreEnabled(false);
                        getGroupMember();
                    }
                });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        groupId = getIntent().getExtras().getString("groupId");
        getGroupFromServer();
        switchGroupMsg.setChecked(SharedPref.getInstance(App.getInstance()).getBoolean(groupId, false));
//        group = EMClient.getInstance().groupManager().getGroup(groupId);
//        if (group.getGroupName().length() > 6) {
//            titleGroupName = group.getGroupName().substring(0,5) + "...";
//        }
//
//        tvTitleName.setText(titleGroupName + "(" + group.getMemberCount() + ")");
//        tvGroupName.setText(group.getGroupName());


    }

    private void getGroupMember() {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                try {
                    List<String> memberList = new ArrayList<>();
                    memberList.add(0, group.getOwner());
                    EMCursorResult<String> result = null;
                    final int pageSize = 1000;
                    do {
                        result = EMClient.getInstance().groupManager().fetchGroupMembers(groupId,
                                result != null ? result.getCursor() : "", pageSize);
                        memberList.addAll(result.getData());
                    } while (result.getData().size() == pageSize);
                    StringBuilder otherId = new StringBuilder();
                    if (memberList.size() > 0) {
                        for (int i = 0; i < memberList.size(); i++) {
                            otherId.append(memberList.get(i));
                            if (memberList.size() - 1 != i) {
                                otherId.append(",");
                            }
                        }
                    }
                    subscriber.onNext(otherId.toString());
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    T.getInstance().showShort("获取群组成员列表失败");
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<String>bindToLifecycle())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        getP().getUserInfo(s);
                    }
                });

    }

    @Override
    protected void initListener() {
        super.initListener();
        RxView.clicks(flBack)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Router.pop(GroupDetailsActivity.this);
                    }
                });

        RxView.clicks(tvGroupName)
                .compose(this.<Void>bindToLifecycle())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (isOwner) {
                            Router.newIntent((Activity) App.getInstance())
                                    .requestCode(233)
                                    .to(ChangeGroupNameActivity.class)
                                    .putString("groupName", group.getGroupName())
                                    .putString("groupId", groupId)
                                    .launch();
                        }
                    }
                });
        switchGroupMsg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    SharedPref.getInstance(App.getInstance()).putBoolean(groupId, true);
                } else {
                    SharedPref.getInstance(App.getInstance()).putBoolean(groupId, false);
                }
            }
        });
    }


    @Override
    public int getLayoutId() {
        return R.layout.antivity_group_details;
    }

    @Override
    public GroupDetailsP newP() {
        return new GroupDetailsP();
    }


    public void getUserInfoFail(String error) {
        T.getInstance().showShort("获取群成员信息失败");
    }

    public void getUserInfoSucceed(List<GetUserInfoBean.DataBean> data) {
        for (int i = 0; i < data.size(); i++) {
            if (group.getOwner().equals(data.get(i).getEid())) {
                data.add(0, data.get(i));
                data.remove(i + 1);
            }
        }
        groupMemberList = data;
        groupMemberListAdapter.setData(groupMemberList);
        groupMemberListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(GetUserInfoBean.DataBean dataBean) {

    }

    @Override
    public void onItemNumClick(GetUserInfoBean.DataBean dataBean) {
        String phone = dataBean.getUser_phone();
        if (CommonUtils.checkPhone(phone)) {
            Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));//跳转到拨号界面，同时传递电话号码
            startActivity(dialIntent);
        }
    }
}
